//对axios进行二次封装
import { notification, Alert, Spin } from 'antd';
import { useNavigate } from 'react-router-dom'
import axios from "axios";

//导入history库, 可以借助该库在组件外跳路由
import { createBrowserHistory } from 'history'

//实例化history对象(用来跳路由)
var history = createBrowserHistory()

//实例化axios实例对象
var service = axios.create({
    // baseURL: 'http://localhost:4000',//设置基准路径
    timeout: 10 * 1000//设置超时时间
})
// var navigate = useNavigate();
//设置请求拦截器
service.interceptors.request.use((config) => {
    //设置请求头
    // config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');
    <Spin tip="Loading...">
        <Alert
            message="Alert message title"
            description="Further details about the context of this alert."
            type="info"
        />
    </Spin>
    return config;
}, (error) => {
    return Promise.reject(error)
})
//设置响应拦截器
service.interceptors.response.use((res) => {
    return res;
}, (error) => {
    // console.log(error.response);
    //处理错误状态码
    if (error.response.status == 401) {
        notification.error({ message: '登陆过期!' });
        //跳转到登录页
        history.push('/login'); //跳转到登录页
        history.go();
        localStorage.removeItem('token'); //删除token
        localStorage.removeItem('userinfo'); //删除userinfo

    } else if (error.response.status == 404) {
        notification.error({ message: '访问路径有误!' });
    } else if (error.response.status == 500) {
        notification.error({ message: '服务器内部错误!' });
    }
    return Promise.reject(error)
})
//抛出
export default service;